// pages/mypage/mypage.js
var media = require("../../utils/media");
var utils = require("../../utils/utils");
Page({

  changeAvatar(){
    const that = this
wx.showModal({
  title: '提示',
  content: '是否更换头像图片',
 
}).then(async r=>{
if(r.confirm){
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success(res) {
      console.log("成功",res);
      that.uploadImage(res.tempFilePaths[0]);
    }
  })
}
})
  },

  uploadImage(fileURL) {
    wx.cloud.uploadFile({
      cloudPath:new Date().getTime()+'.png', // 上传至云端的路径
      filePath: fileURL, // 小程序临时文件路径
      success: res => {
        // 返回文件 ID
        console.log("上传成功",res)
        //获取文件路径
        this.setData({
          imgURL:res.fileID
        })
        this.updateUserInfo()
      },
      fail: console.error
    })
  },
  async updateUserInfo(){
    wx.showLoading({
      title: 'Loading',
    })
wx.cloud.database().collection('user').where({
  _openid:this.data.userOpenid
}).update({
  data:{
    nicKName:this.data.currentName,
    avatarUrl:this.data.imgURL
  }
}).then(r=>{
  wx.showToast({
    title: '修改成功',
  })
  this.getUserInfo()
})
  },
  data: {
    miniprogram_name: utils.miniprogram_name,

    avatarUrl: media.avatarUrl,
userOpenid:'',
    green_arrow: media.green_arrow,

    statement: media.statement,
    note: media.note,

    users: media.users,
    contact: media.contact,

    support: media.support,
    sponsor: media.sponsor,

    chat: media.chat,
    feedback: media.feedback,

    share: media.share,

    miniprogramming_ma: media.miniprogramming_ma,

    admin: media.admin,
  },

  onLoad: function () {

  },

  changeNickName(){
  wx.showModal({
    title: '修改昵称',
    content: this.data.currentName,
    editable:true
  }).then(r=>{
    if(r.confirm){
      this.data.currentName = r.content
      this.updateUserInfo()
    }
  })
  },
  onShow(){
  this.setData({
    userOpenid:wx.getStorageSync('openid') || '',
    userInfo:wx.getStorageSync('userInfo')|| {},
   
  })
  if(wx.getStorageSync('userInfo')._id){
    this.data.currentName = wx.getStorageSync('userInfo').nicKName
  this.data.imgURL = wx.getStorageSync('userInfo').avatarUrl
  }
  },

  // 用户点击右上角分享
  onShareAppMessage() {},
toLogin(){
wx.showLoading({
  title:'登录中'
})
wx.cloud.callFunction({
  name:'get_openid'
}).then(r=>{
  console.log(r)
  wx.setStorageSync('openid', r.result.openid)
  this.setData({
    userOpenid:r.result.openid
  })
  this.getUserInfo()
  wx.hideLoading()
})
},

async getUserInfo(){
const res =await wx.cloud.database().collection('user').where({_openid:this.data.userOpenid}).get()
if(res.data.length>0){
  //用户存在
  this.setData({
    userInfo:res.data[0]
  })
  wx.setStorageSync('userInfo', res.data[0])
  return 
}
//用户不存在
const datas = {
  avatarUrl:'https://th.bing.com/th/id/OIP.X-VG5gTN2ak8rGRij3oCogAAAA?rs=1&pid=ImgDetMain',
  nicKName:'用户'+Math.floor(Math.random()*1000)+1,
}
wx.cloud.database().collection('user').add({
  data:datas
})
// 递归查询信息
this.getUserInfo()
},

toLogout(){
this.setData({
  userOpenid:''
})
wx.setStorageSync('openid', null)
},
  // 用户点击右上角分享到朋友圈
  onShareTimeline: function (res) {},

  // 软件声明
  tostatement() {
    wx.navigateTo({
      url: "../../pages/more/statement/statement",
    });
  },
  // 特别说明
  aboutus() {
    wx.showModal({
      title: "特别说明",
      content:
        "本项目同时应用于2023年中国大学生计算机设计大赛，未经允许，不得随意用于各类比赛项目\n\n作品名：云上高校导航\n作品编号：2023042719\n奖项：广西赛区 软件应用与开发 - 移动应用开发（非游戏类） 三等奖",
    });
  },
  // 联系作者
  contact() {
    wx.showModal({
      title: "联系作者",
      content: "如果遇到什么问题\n请点击确认与我联系",
      success: (res) => {
        if (res.confirm == true) {
          wx.previewImage({
            current: this.data.contact, // 当前显示图片的http链接
            urls: [this.data.contact], // 需要预览的图片http链接列表
          });
        }
      },
      fail(res) {
        console.log("fail");
      },
    });
  },
  // 给点赞助
  sponsor() {
    wx.showModal({
      title: "给点赞助",
      content: "如果你觉得小程序不错\n可以支持一下开发者",
      success: (res) => {
        if (res.confirm == true) {
          wx.previewImage({
            current: this.data.sponsor,
            urls: [this.data.sponsor],
          });
        }
      },
      fail(res) {
        console.log("fail");
      },
    });
  },

  // 分享
  share() {
    wx.showModal({
      title: "推荐给好友",
      content: "点击确认即可查看小程序码\n长按小程序码即可转发给好友",
      success: (res) => {
        if (res.confirm == true) {
          wx.previewImage({
            current: this.data.miniprogramming_ma, // 当前显示图片的http链接
            urls: [this.data.miniprogramming_ma], // 需要预览的图片http链接列表
          });
        }
      },
      fail(res) {
        console.log("fail");
      },
    });
  },

  // 管理界面
  toadmin() {
    wx.cloud.callFunction({
      name: "login",
      complete: (res) => {
        // console.log(res.result.data.length)
        if (res.result.data.length != 0) {
          // console.log(res.result.data[0].name)
          var name = res.result.data[0].name;

          wx.showToast({
            title: "欢迎回来\n管理员：" + name,
            icon: "none",
            duration: 1500,
          });
          setTimeout(() => {
            wx.navigateTo({
              url: "../../pages/admin/admin",
            });
          }, 1500);
        } else {
          wx.showToast({
            title: "抱歉，同志\n您还不是管理员哦",
            icon: "none",
            duration: 1500,
          });
        }
      },
    });
  },

  // 获取openid
  getopenid() {
    wx.cloud.callFunction({
      name: "get_openid",
      complete: (res) => {
        console.log("微信用户openid", res.result.openid);
        let openid = res.result.openid;
        wx.showModal({
          title: "您的openid",
          content: openid,
          confirmText: "点击复制",
          complete: (res) => {
            if (res.confirm) {
              wx.setClipboardData({
                data: openid,
                success(res) {
                  wx.getClipboardData({
                    success(res) {
                      console.log(res.data); // data
                    },
                  });
                },
              });
            }
          },
        });
      },
    });
  },
});
